package com.example.flashsales.Tools;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class TokenTool {
    private static String SIGNATURE = "token!@#$%^7890";
    /**
     * 生成Token
     * @param map
     * @return
     */
    public static String createToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k, v);
        });
        //添加过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,300000);

        builder.withExpiresAt(calendar.getTime());
        builder.withIssuer("gxh");
        return builder.sign(Algorithm.HMAC256("ergdua"));
    }

    /**
     * 验证token
     * @param token
     */
    public static void verify(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256("ergdua")).withIssuer("gxh").build();
        build.verify(token);
    }

    /**
     * 获取token中payload
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token){
        return JWT.require(Algorithm.HMAC256("ergdua")).withIssuer("gxh").build().verify(token);
    }
}
